package de.tsajar.es.character;

import com.jme3.app.Application;
import com.jme3.app.state.AppStateManager;
import com.jme3.bullet.BulletAppState;
import com.jme3.bullet.PhysicsSpace;
import com.jme3.math.Vector3f;
import com.simsilica.es.Entity;
import com.simsilica.es.EntityId;
import com.simsilica.es.EntitySet;
import de.tsajar.es.EntitySystemAppState;
import de.tsajar.es.position.PositionComponent;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

/**
 *
 * @author Eike Foede
 */
public class CharacterControlSystem extends EntitySystemAppState {

    private Map<EntityId, BetterCharacterControlExtend> controls = new HashMap<EntityId, BetterCharacterControlExtend>();
    EntitySet es;
    EntitySet jumps;
    PhysicsSpace ps;

    @Override
    public void initialize(AppStateManager stateManager, Application app) {
        super.initialize(stateManager, app);
        es = ed.getEntities(CharacterControlComponent.class, WalkDirectionComponent.class, PositionComponent.class);
        jumps = ed.getEntities(CharacterControlComponent.class, JumpComponent.class);
        ps = stateManager.getState(BulletAppState.class).getPhysicsSpace();
        for (Entity e : es) {
            entityAdded(e);
        }
    }

    @Override
    public void update(float tpf) {
        es.applyChanges();
        jumps.applyChanges();
        for (Entity e : jumps.getAddedEntities()) {
            controls.get(e.getId()).jump();
            ed.removeComponent(e.getId(), JumpComponent.class);
        }
        for (Entity e : es.getAddedEntities()) {
            entityAdded(e);
        }
        for (Entity e : es.getChangedEntities()) {
            entityChanged(e);
        }
        for (Entity e : es.getRemovedEntities()) {
            entityRemoved(e);
        }
        for (Entry<EntityId, BetterCharacterControlExtend> entry : controls.entrySet()) {
            entry.getValue().update(tpf);
            ed.setComponent(entry.getKey(), new PositionComponent(entry.getValue().getLocation()));
        }
    }

    private void entityAdded(Entity e) {
        BetterCharacterControlExtend bcc = new BetterCharacterControlExtend(1f, 2f, 0.5f);
        bcc.warp(e.get(PositionComponent.class).getPosition());

        Vector3f walkDir = e.get(WalkDirectionComponent.class).getWalkDirection();
        bcc.setWalkDirection(walkDir);
        ps.add(bcc);
        
//        bcc.setEnabled(true);
        controls.put(e.getId(), bcc);
    }

    private void entityChanged(Entity e) {
        controls.get(e.getId()).setWalkDirection(e.get(WalkDirectionComponent.class).getWalkDirection());
    }

    private void entityRemoved(Entity e) {
    }
}
